package com.anuo.app.common.utils;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;

public class ReflectionUtil {

    /**
     * 获取一个对象的所有字段(包括父类的)
     *  参考: //https://stackoverflow.com/questions/1042798/retrieving-the-inherited-attribute-names-values-using-java-reflection
     *
     * @param fields
     * @param type
     * @return
     */
    public static List<Field> getAllFields(List<Field> fields, Class<?> type) {
        fields.addAll(Arrays.asList(type.getDeclaredFields()));

        if (type.getSuperclass() != null) {
            getAllFields(fields, type.getSuperclass());
        }

        return fields;
    }

    /**
     * 获取一个对象的属性值
     *  参考:https://stackoverflow.com/questions/2043471/in-java-how-to-get-attribute-given-the-string-with-its-name
     * @param obj
     * @param fieldName
     * @param <T>
     * @return
     * @throws NoSuchFieldException
     * @throws IllegalAccessException
     */
    public static <T> String getFieldValue(T obj, String fieldName) throws NoSuchFieldException, IllegalAccessException {
        Class<?> classz = obj.getClass();
        Field field = classz.getDeclaredField(fieldName);
        field.setAccessible(true);
        return (String) field.get(obj);
    }

}
